import React, { Component } from 'react';
import store from '../store';

export default class ReduxPage extends Component {
  componentDidMount() {
    this.unsubscribe = store.subscribe(() => {
      this.forceUpdate();
    });
  }
  componentWillUnmount() {
    this.unsubscribe && this.unsubscribe();
  }

  addState = () => {
    store.dispatch({ type: 'ADD', payload: 100 });
  };

  asyncAddState = () => {
    // setTimeout(() => {
    //   store.dispatch({ type: 'ADD', payload: 100 });
    // }, 100);

    store.dispatch((dispatch) => {
      setTimeout(() => {
        dispatch({ type: 'ADD', payload: 100 });
      }, 1000);
    });
  };

  promiseAddState = () => {
    store.dispatch(Promise.resolve({ type: 'ADD', payload: 110 }));
  };

  minusState = () => {
    store.dispatch({ type: 'MINUS', payload: 100 });
  };

  render() {
    return (
      <div>
        <h3>ReduxPage</h3>
        <div>{store.getState().count}</div>
        <button onClick={this.addState}>add</button>
        <button onClick={this.asyncAddState}>asyncAdd</button>
        <button onClick={this.promiseAddState}>promiseAdd</button>
        <button onClick={this.minusState}>minus</button>
      </div>
    );
  }
}
